module Magicloud.Map where

import qualified Data.Map as M
import Control.Monad

mapM :: (Monad m, Ord k) => (a -> m b) -> M.Map k a -> m (M.Map k b)
mapM f m = 
  let (ks, as) = unzip $ M.toList m
  in
    Prelude.mapM f as >>=
      return . M.fromList . zip ks

mapWithKeyM :: (Monad m, Ord k) => (k -> a -> m b) -> M.Map k a -> m (M.Map k b)
mapWithKeyM f m =
  (Prelude.mapM (\(k, a) -> do
                  b <- f k a
                  return (k, b)
                ) $ M.toList m) >>=
    return . M.fromList

filterWithKeyM :: (Monad m, Ord k) => (k -> a -> m Bool) -> M.Map k a -> m (M.Map k a)
filterWithKeyM p m =
  Control.Monad.filterM (\(k, a) -> p k a) (M.toList m) >>=
    return . M.fromList
